package exam.web.action;

import java.util.Date;
import java.util.List;

import exam.common.constant.CommonConstant;
import exam.common.util.CommonUtil;
import exam.common.util.NullCheckUtil;
import exam.common.util.StringUtils;
import exam.model.dao.SubQuestionDAO;
import exam.model.entity.TAnswerEntity;
import exam.model.entity.TQuestionEntity;
import exam.model.entity.TSubQuestionEntity;
import exam.model.entity.TUserEntity;
import exam.web.action.base.QuestionActionBase;

public class AddQuestionAction extends QuestionActionBase {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<TSubQuestionEntity> listSubQuestion;
	
	private SubQuestionDAO subQuestDAO = new SubQuestionDAO();
	
	private boolean type;
	@Override
	public String execute() throws Exception {
		String port = null;
		listSubQuestion = subQuestDAO.selectListSubQuestion();
		if (NullCheckUtil.isNUll(tQuestionEntity.getQuestionContent()) 
				|| CommonUtil.lengthObject(tQuestionEntity.getQuestionContent()) == 0) {
			addActionMessage(getText("Nhập thông tin câu hỏi"));
			port = INPUT;
		} else {
			tQuestionEntity.setCreateDate(new Date());
			tQuestionEntity.setUpdateDate(new Date());
			tQuestionEntity.setQuestionType(isType()?1:0);
			tQuestionEntity.setSubQuestionEntity(new TSubQuestionEntity(tQuestionEntity.getSubQuestId()));
			tQuestionEntity.setUserEntity(new TUserEntity(tQuestionEntity.getUserId()));
			questionDAO.insertQuestion(tQuestionEntity);
			addActionMessage(getText("Thêm câu hỏi thành công"));
			addAnswer(tQuestionEntity);
			port = SUCCESS;
		}
		return port;
	}

	private void addAnswer(TQuestionEntity questionEntity) {
		// danh sach noi dung dap an
		String[] answerContents = request.getParameterValues("answerContents");
		long questionId = (Long) questionDAO.maxQuestionId();
		questionEntity.setQuestionId(questionId);
		TAnswerEntity answerEntity = null;
		int correct;
		for(int i = 0; i < answerContents.length; i++) {
			if(StringUtils.isNotEmpty(answerContents[i])) {
				answerEntity = new TAnswerEntity();
				answerEntity.setAnswerContent(answerContents[i]);
				correct = CommonConstant.ONE.equals(request.getParameter("correct_" + i))?1:0;
				answerEntity.setAnswerCorrect(correct);
				answerEntity.setQuestionEntity(questionEntity);
				answerDAO.insert(answerEntity);
			}
		}
	}
	
	public List<TSubQuestionEntity> getListSubQuestion() {
		return listSubQuestion;
	}

	public void setListSubQuestion(List<TSubQuestionEntity> listSubQuestion) {
		this.listSubQuestion = listSubQuestion;
	}

	public boolean isType() {
		return type;
	}

	public void setType(boolean type) {
		this.type = type;
	}

}
